package com.lvt.design.pattern.module.stat.v3;

import com.google.gson.Gson;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 负责一定频率统计并发送到命令行
 *
 * @author LT
 * @date 2023年02月22日 22:40
 */
public class ConsoleReporter {

    private MetricsStorage metricsStorage;
    private Aggregator aggregator;
    private StatViewer statViewer;
    private ScheduledExecutorService executorService;

    public ConsoleReporter() {
    }

    public ConsoleReporter(MetricsStorage metricsStorage, Aggregator aggregator, StatViewer statViewer) {
        this.metricsStorage = metricsStorage;
        this.aggregator = aggregator;
        this.statViewer = statViewer;
        this.executorService = Executors.newSingleThreadScheduledExecutor();
    }

    public void startRepeatedReport(long periodInSeconds, long durationInSeconds) {
        executorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                long durationInMills = durationInSeconds * 1000;
                long endTimeInMills = System.currentTimeMillis();
                long startTimInMills = endTimeInMills - durationInMills;
                Map<String, List<RequestInfo>> requestInfos = metricsStorage.getRequestInfos(startTimInMills, endTimeInMills);
                Map<String, RequestStat> requestStats = aggregator.aggregate(requestInfos, durationInMills);
                statViewer.output(requestStats, startTimInMills, endTimeInMills);
            }
        }, 0, periodInSeconds, TimeUnit.SECONDS);
    }
}
